package com.example.emailcraft.service.impl;

import com.example.emailcraft.entity.request.EmailRequest;
import com.example.emailcraft.interceptor.CurrentUserHolder;
import com.example.emailcraft.mapper.UsersMapper;
import com.example.emailcraft.service.IEmailService;
import com.example.emailcraft.utils.RoleUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.regex.Pattern;
@Service
public class EmailServiceImpl implements IEmailService {
    @Autowired
    private RoleUtils roleUtils;

    @Autowired
    private UsersMapper usersMapper;
    @Override
    public void sendEmail(EmailRequest  request) throws Exception {
        // 获取当前用户角色
        String roles = CurrentUserHolder.getRequired().getRoles();
        //鉴权
        if (!roleUtils.isUser(roles)) {
            throw new IllegalArgumentException("普通用户无权限发送邮件");
        }



        // 1. 参数校验增强
        validateEmailRequest(request);

        // 2. 创建邮件客户端（复用配置）
        JavaMailSenderImpl mailSender = createMailSender(request);

        // 3. 构建完整邮件
        MimeMessage message = buildMimeMessage(mailSender, request);

        // 4. 发送邮件（带重试机制）
        sendWithRetry(mailSender, message);
    }

// ========== 私有方法 ==========

    /**
     * 参数校验
     */
    private void validateEmailRequest(EmailRequest request) {
        if (StringUtils.isEmpty(request.getHtmlContent()) &&
                StringUtils.isEmpty(request.getTextContent())) {
            throw new IllegalArgumentException("邮件正文内容不能为空");
        }
        if (!Pattern.matches("^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}$", request.getToEmail())) {
            throw new IllegalArgumentException("收件人邮箱格式错误");
        }
    }

    /**
     * 创建邮件客户端
     */
    private JavaMailSenderImpl createMailSender(EmailRequest request) {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.qq.com");
        mailSender.setPort(465);
        mailSender.setUsername(request.getFromEmail());
        mailSender.setPassword(request.getSmtpPassword());

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.connectiontimeout", "5000"); // 5秒连接超时
        props.put("mail.smtp.timeout", "10000");         // 10秒操作超时
        mailSender.setJavaMailProperties(props);

        return mailSender;
    }

    /**
     * 构建完整邮件
     */
    private MimeMessage buildMimeMessage(JavaMailSenderImpl mailSender, EmailRequest request)
            throws MessagingException, IOException {

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        // 基础信息
        helper.setFrom(request.getFromEmail());
        helper.setTo(request.getToEmail().split(";"));
        helper.setSubject(request.getSubject());

        // 设置正文
        if (StringUtils.hasText(request.getHtmlContent())) {
            helper.setText(request.getHtmlContent(), true);
        } else {
            helper.setText(request.getTextContent(), false);
        }

        // 添加多个附件
        addAttachments(helper, request.getAttachments());

        return message;
    }

    /**
     * 添加附件（支持多个）
     */
    private void addAttachments(MimeMessageHelper helper, List<MultipartFile> attachments)
            throws MessagingException, IOException {

        if (attachments != null && !attachments.isEmpty()) {
            for (MultipartFile file : attachments) {
                if (!file.isEmpty()) {
                    helper.addAttachment(
                            MimeUtility.encodeText(Objects.requireNonNull(file.getOriginalFilename()), "UTF-8", "B"),
                            new ByteArrayResource(file.getBytes())
                    );
                }
            }
        }
    }

    /**
     * 带重试机制的发送
     */
    private void sendWithRetry(JavaMailSenderImpl mailSender, MimeMessage message) {
        int maxRetries = 3;
        for (int i = 0; i < maxRetries; i++) {
            try {
                mailSender.send(message);
                return;
            } catch (MailException e) {
                if (i == maxRetries - 1) {
                    throw e;
                }
                try {
                    Thread.sleep(1000 * (i + 1));
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new MailSendException("邮件发送被中断", ie);
                }
            }
        }
    }
}
